from django.shortcuts import render, redirect
from app01 import models
from django import forms
# 验证方式1：引入对模型的正则表达式
from django.core.validators import RegexValidator
# 验证方式2
from django.core.exceptions import ValidationError
# 后端代码安全标记到前端
from django.utils.safestring import mark_safe
#分页组件类
from app01.utils.pagination import Pagination

from app01.utils.bootstrap import BootStrapModelForm

from app01.utils.form import UserModelForm,PrettyModelForm,PrettyEditModelForm

#------------------靓号管理----------------------------------------------------------


def pretty_list(request):
    """靓号列表"""
    # 搜索字典
    data_dict = {}
    value = request.GET.get("q", "")
    if value:
        data_dict["mobile__contains"] = value
    #获取查找值
    queryset = models.PrettyNum.objects.filter(**data_dict).order_by("-level")
    # 分页组件类实例化
    page_object = Pagination(request,queryset)
    #参数字典
    contex = {
        "value": value,#数据库搜索值
        "qureyset": page_object.page_queryset,#分完页的数据
        "page_string": page_object.html(),#生成的页码
    }
    return render(request, "pretty_list.html", contex)

def pretty_add(request):
    """添加靓号"""
    if request.method == "GET":
        form = PrettyModelForm()
        return render(request, 'pretty_add.html', {"form": form})
    form = PrettyModelForm(data=request.POST)
    if form.is_valid():  # 校验成功
        form.save()
        return redirect("/pretty/list/")
    return render(request, 'pretty_add.html', {'form': form})

def pretty_edit(request, nid):
    """编辑靓号"""
    # 获取当前行数据
    row_object = models.PrettyNum.objects.filter(id=nid).first()
    if request.method == "GET":
        # 将默认值传递给页面
        form = PrettyEditModelForm(instance=row_object)
        return render(request, 'pretty_edit.html', {"form": form})
    # 处理post请求
    form = PrettyEditModelForm(data=request.POST, instance=row_object)
    # 校验
    if form.is_valid():
        form.save()
        return redirect("/pretty/list/")
    return render(request, 'pretty_edit.html', {"form": form})

def pretty_delete(request):
    """删除靓号"""
    nid = request.GET.get("nid")
    models.PrettyNum.objects.filter(id=nid).delete()
    return redirect("/pretty/list/")
